﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class FriendFSM : CommonFSM
{

    protected bool m_bSelectChk = false;

    protected bool m_bDestinationInvalid = false;


    protected float m_fTimer;
    protected bool m_bFootStep;

    [HideInInspector]
    protected GameObject m_pSelectUI;
    [HideInInspector]
    protected GameObject m_pHoverUI;

    protected Vector3 m_vecPrevPos;

    protected virtual void SetState(BASEUNIT_STATE iStateKey)
    {
    }

    protected virtual bool MouseColCheck()
    {

        int iMouseIdx = Calculate.GetMyTileIdx(Calculate.GetMousePos());

        if(iMouseIdx == Calculate.GetMyTileIdx(gameObject.transform.position))
            return true;

        return false;
    }


    //------------------------------State Change---------------------------------


    //MoveOrder
    protected virtual void MoveOrder()
    {

        if (MouseColCheck() && GameObject.Find("RightWdw").GetComponent<RightWdwMgr>().CurWinNum == 0)
        {
            if (m_pHoverUI == null)
                m_pHoverUI = ResourceMgr.GetInstance().CreateHoverUnitInformUI(gameObject);

            if (m_pSelectUI == null)
            {
                m_pSelectUI = ResourceMgr.GetInstance().CreateSelectUI(gameObject);
                m_pSelectUI.GetComponent<SelectUI>().m_pOwner = gameObject;
                m_pSelectUI.GetComponent<SelectUI>().SetAlpha(0.3f);
            }


            //상태이상 출력
            for (int i = 0; i < gameObject.GetComponent<UnitStatus>().m_unitData.m_List_ConditionStrange.Count; ++i)
            {
                if (gameObject.GetComponent<UnitStatus>().m_unitData.m_List_ConditionStrange[i] != null)
                    gameObject.GetComponent<UnitStatus>().m_unitData.m_List_ConditionStrange[i].active = true;
            }

            if (Input.GetMouseButtonDown(0) && (!m_bSelectChk))
            {
                if (InputMgr.GetInstance().m_bUnitSelected == true)
                {
                    Debug.Log(InputMgr.GetInstance().m_bUnitSelected);
                    return;
                }

                if (InputMgr.GetInstance().m_MouseInputState == MOUSEINPUT_STATE.NORMAL)
                {
                    GameObject.Find("SceneDataMgr").GetComponent<SceneDataMgr>().SelectedUnit = gameObject;
                    m_bSelectChk = true;

                    InputMgr.GetInstance().m_bUnitSelected = true;

                    if (m_pSelectUI != null)
                        m_pSelectUI.GetComponent<SelectUI>().SetAlpha(1.0f);
                }
                else if (InputMgr.GetInstance().m_MouseInputState == MOUSEINPUT_STATE.SUPPLY)       //무기 보급
                {
                    InputMgr.GetInstance().m_MouseInputState = MOUSEINPUT_STATE.NORMAL;
                    gameObject.GetComponent<UnitStatus>().m_WeaponData = GameObject.Find("SceneDataMgr").GetComponent<SceneDataMgr>().SupplyWeaponQueue;
                    GameObject.Find("SceneDataMgr").GetComponent<SceneDataMgr>().ArmoryWeaponList.Remove(GameObject.Find("SceneDataMgr").GetComponent<SceneDataMgr>().SupplyWeaponQueue);

                    string strType = "null";

                    if (gameObject.GetComponent<UnitStatus>().m_WeaponData.m_WeaponType == WEAPON_TYPE.PISTOL)
                    {
                        strType = "Pistol";
                        gameObject.transform.GetChild(1).GetComponent<AudioSource>().clip = Resources.Load<AudioClip>("Audio/Pistol");
                        gameObject.transform.GetChild(1).GetComponent<Animator>().runtimeAnimatorController = Resources.Load<RuntimeAnimatorController>("Anim/Weapon/Pistol");
                    }
                    else if (gameObject.GetComponent<UnitStatus>().m_WeaponData.m_WeaponType == WEAPON_TYPE.RIFLE)  
                    {
                        if (gameObject.GetComponent<UnitStatus>().m_WeaponData.m_strWeaponName == "FN303")
                        {
                            gameObject.transform.GetChild(1).GetComponent<AudioSource>().clip = Resources.Load<AudioClip>("Audio/Weapon/FN303/4");
                            gameObject.transform.GetChild(1).GetComponent<Animator>().runtimeAnimatorController = Resources.Load<RuntimeAnimatorController>("Anim/Weapon/Riotgun");
                        }
                        else
                        {
                            gameObject.transform.GetChild(1).GetComponent<AudioSource>().clip = Resources.Load<AudioClip>("Audio/Rifle");
                            gameObject.transform.GetChild(1).GetComponent<Animator>().runtimeAnimatorController = Resources.Load<RuntimeAnimatorController>("Anim/Weapon/Rifle");
                        }
                        strType = "Rifle";
                    }
                    else if (gameObject.GetComponent<UnitStatus>().m_WeaponData.m_WeaponType == WEAPON_TYPE.CLOSE)
                    {
                        strType = "Close";
                        gameObject.transform.GetChild(1).GetComponent<Animator>().runtimeAnimatorController = Resources.Load<RuntimeAnimatorController>("Anim/Weapon/Close");
                    }

                    string s = string.Format("{0}{1}{2}{3}", "Anim/Unit/", gameObject.transform.parent.parent.name, "/" ,strType);
                    gameObject.GetComponent<Animator>().runtimeAnimatorController = Resources.Load<RuntimeAnimatorController>(s);


                    GameObject.Find("MainCamera").GetComponent<AudioSource>().PlayOneShot(Resources.Load<AudioClip>("Audio/Reload0"));
                }
            }
        }
        else if (!MouseColCheck())
        {
            if (!m_bSelectChk)
            {
                if (m_pSelectUI != null)
                    Destroy(m_pSelectUI);
            }
            if (!InputMgr.GetInstance().m_bUnitHoverUI)
            {
                if (m_pHoverUI != null)
                    Destroy(m_pHoverUI);
            }

            //상태이상 출력 삭제
            for (int i = 0; i < gameObject.GetComponent<UnitStatus>().m_unitData.m_List_ConditionStrange.Count; ++i)
            {
                if (gameObject.GetComponent<UnitStatus>().m_unitData.m_List_ConditionStrange[i] != null)
                    gameObject.GetComponent<UnitStatus>().m_unitData.m_List_ConditionStrange[i].active = false;
            }
        }

        //Mouse MovePos Select
        if (Input.GetMouseButtonUp(1) && m_bSelectChk)
        {
            m_bSelectChk = false;
            GameObject.Find("SceneDataMgr").GetComponent<SceneDataMgr>().SelectedUnit = null;

            m_vecDest = Calculate.GetMousePos();

            InputMgr.GetInstance().m_bUnitSelected = false;

            //End
            if (!Calculate.AStarStart(gameObject, m_vecDest, ref m_BestList, m_iPrevTIleIdx, m_iPrevTileOption))
                gameObject.GetComponent<UnitStatus>().m_unitData.m_CurrentUnitState = BASEUNIT_STATE.MOVE;

            Destroy(m_pSelectUI);
        }
    }



    //CoverState

    protected virtual void CoverEnable()
    {

        if (gameObject.GetComponent<UnitStatus>().m_unitData.m_Cover != null)
                gameObject.GetComponent<UnitStatus>().m_unitData.m_CurrentUnitState = BASEUNIT_STATE.COVER;


    }

    protected virtual void SupplyEnable()
    {
        if (GameObject.Find("SceneDataMgr").GetComponent<SceneDataMgr>().AmmoDumpList.Count == 0)
            return;

        if (gameObject.GetComponent<UnitStatus>().m_WeaponData.m_iCurrentAmmo == 0
            && gameObject.GetComponent<UnitStatus>().m_unitData.iHavMagazine == 0)
        {

            m_vecDest = GameObject.Find("SceneDataMgr").GetComponent<SceneDataMgr>().AmmoDumpList[0].transform.position;
            Calculate.AStarStart(gameObject, m_vecDest, ref m_BestList, m_iPrevTIleIdx, m_iPrevTileOption);
            m_BestList = gameObject.GetComponent<AStar>().GetBestList();


            m_vecPrevPos = gameObject.transform.position;
            m_bSupply = true;
            gameObject.GetComponent<UnitStatus>().m_unitData.m_CurrentUnitState = BASEUNIT_STATE.MOVE;
        }
            
    }

    protected virtual void CloseAtkEnable()
    {
        if (m_ObjCloseAtkTarget != null)
        {
            List<int> SurrTile = Calculate.GetAllSurroundingTile(m_iCurrentTileIdx);

            for (int i = 0; i < SurrTile.Count; ++i)
            {

                if (SurrTile[i] == m_ObjCloseAtkTarget.GetComponent<CommonFSM>().m_iCurrentTileIdx)
                {
                    gameObject.GetComponent<UnitStatus>().m_unitData.m_CurrentUnitState = BASEUNIT_STATE.CLOSEATTACK;
                    break;
                }
            }
        }

    }

    protected virtual void AimEnable()
    {
        if (EnemyTarget_Find("Enemy")
            && gameObject.GetComponent<UnitStatus>().m_WeaponData.m_iCurrentAmmo > 0)
        {
            if (m_ObjTarget.GetComponent<UnitStatus>().m_unitData.m_CurrentUnitState != BASEUNIT_STATE.DEAD)
            gameObject.GetComponent<UnitStatus>().m_unitData.m_CurrentUnitState = BASEUNIT_STATE.AIM;
            
        }
    }

    protected virtual bool ReloadEnalbe()
    {
        if (gameObject.GetComponent<UnitStatus>().m_unitData.iHavMagazine <= 0)
            return false;

        if (gameObject.GetComponent<UnitStatus>().m_WeaponData.m_iCurrentAmmo <= 0
        && gameObject.GetComponent<UnitStatus>().m_unitData.m_CurrentUnitState != BASEUNIT_STATE.CLOSEATTACK
            && gameObject.GetComponent<UnitStatus>().m_unitData.m_CurrentUnitState != BASEUNIT_STATE.DAMAGE)
        {
            gameObject.GetComponent<UnitStatus>().m_unitData.m_CurrentUnitState = BASEUNIT_STATE.RELOAD;
            return true;
        }

        return false;
    }

    protected virtual bool CommonState()
    {
        UnitData unitstat = gameObject.GetComponent<UnitStatus>().m_unitData;

        //if (unitstat.iHavMagazine <= 1)
            //Add_ConditionStrange(CONDITION_STRANGE.AMMO_LOW);


        //BlockTile Make
        List<GameObject> ListTile = GameObject.Find("DebugTile").GetComponent<Background>().m_ListTile;


        if (gameObject.GetComponent<UnitStatus>().m_unitData.m_CurrentUnitState != BASEUNIT_STATE.MOVE)
        {
            int iTileidx = Calculate.GetMyTileIdx(transform.position);

            if (ListTile[iTileidx].GetComponent<Tile>().m_iOption != (int)TILE_OPTION.BLOCK)
            {
                m_iCurrentTileIdx = iTileidx;
                m_iPrevTileOption = ListTile[m_iPrevTIleIdx = iTileidx].GetComponent<Tile>().m_iOption;
                ListTile[m_iPrevTIleIdx = iTileidx].GetComponent<Tile>().m_iOption = (int)TILE_OPTION.BLOCK;
            }
        }


        //State
        if (gameObject.GetComponent<UnitStatus>().m_unitData.iCurrentHP <= 0)
        {
            gameObject.GetComponent<UnitStatus>().m_unitData.m_CurrentUnitState = BASEUNIT_STATE.DEAD;
            return true;
        }
        else
        {
            //if (gameObject.GetComponent<UnitStatus>().m_unitData.iCurrentMorale <= 0)
            //{
            //    gameObject.GetComponent<UnitStatus>().m_unitData.m_CurrentUnitState = BASEUNIT_STATE.RETREAT;
            //    return true;
            //}
        }

        return false;
    }

    protected virtual void Add_ConditionStrange(CONDITION_STRANGE _CSID)
    {
        UnitData unitstat = gameObject.GetComponent<UnitStatus>().m_unitData;

        //Ammo low
        for (int i = 0; i < unitstat.m_List_ConditionStrange.Count; ++i)
        {
            if (unitstat.m_List_ConditionStrange[i].GetComponent<ConditionStrange>().iCS_ID == _CSID)
                return;
        }

        GameObject objCSUI = Instantiate(ResourceMgr.GetInstance().m_CSUI, gameObject.transform.position, Quaternion.identity) as GameObject;
        objCSUI.GetComponent<ConditionStrange>().iCS_ID = _CSID;
        objCSUI.GetComponent<ConditionStrange>().m_pOwner = gameObject;
        unitstat.m_List_ConditionStrange.Add(objCSUI);

    }


    void OnTriggerStay2D(Collider2D CollObj)
    {
        if (CollObj.gameObject.tag == "Enemy")
            if (CollObj.gameObject.GetComponent<UnitStatus>().m_unitData.m_CurrentUnitState != BASEUNIT_STATE.DEAD)
                m_ObjCloseAtkTarget = CollObj.gameObject;

        if (CollObj.gameObject.tag == "Cover")
        {
            if (CollObj.gameObject.GetComponent<Build>().bStructComplete)
            {
                gameObject.GetComponent<UnitStatus>().m_unitData.m_Cover = CollObj.gameObject;
            }
        }
    }

    void OnTriggerExit2D(Collider2D CollObj)
    {
        if (CollObj.gameObject.tag == "Enemy")
            m_ObjCloseAtkTarget = null;

        if (CollObj.gameObject.tag == "Cover")
            gameObject.GetComponent<UnitStatus>().m_unitData.m_Cover = null;
    }

    void OnDestinationInvalid() // 목적지가 장애물내부일때 목적지도달시 멈추도록
    {
        m_bDestinationInvalid = true;
    }

    protected void CheckValidDest()
    {
        if (m_bDestinationInvalid)
        {
            //if (!GetComponent<PolyNavAgent>().hasPath && transform.parent.parent.gameObject != GameObject.Find("Engineers").gameObject)
            //{
            //    gameObject.GetComponent<UnitStatus>().m_unitData.m_CurrentUnitState = BASEUNIT_STATE.IDLE;
            //    m_bDestinationInvalid = false;
            //}
        }
    }


    protected void FootStep()
    {
        m_fTimer += Time.deltaTime;
        if (m_fTimer >= GetComponent<Animator>().GetCurrentAnimatorStateInfo(0).length / 2)
        {
            if (m_bFootStep)
            {

                GetComponent<AudioSource>().PlayOneShot(Resources.Load<AudioClip>("Audio/Footstep_0"));
                m_bFootStep = false;
            }
            else
            {
                GetComponent<AudioSource>().PlayOneShot(Resources.Load<AudioClip>("Audio/Footstep_1"));
                m_bFootStep = true;
            }

            m_fTimer = 0.0f;
        }
    }

    protected void CloseAtkSound()
    {
        m_fTimer += Time.deltaTime;
        if (m_fTimer >= GetComponent<Animator>().GetCurrentAnimatorStateInfo(0).length)
        {
            GetComponent<AudioSource>().PlayOneShot(Resources.Load<AudioClip>(string.Format("Audio/Whip_{0}", Random.Range(0, 2))));
            m_bFootStep = false;

            m_fTimer = 0.0f;
        }
    }

    public void Chat(CHATBUBBLE_STATE state, int SceneID = 0, int Log_Num = 0) 
    {
        if (state == CHATBUBBLE_STATE.NORMAL)
        {
            gameObject.GetComponent<UnitStatus>().m_unitData.fCurChat += gameObject.GetComponent<UnitStatus>().m_unitData.fChatty * Time.deltaTime * Random.Range(1, 5);

            if (gameObject.GetComponent<UnitStatus>().m_unitData.fCurChat > 100.0f && gameObject.GetComponent<UnitStatus>().m_unitData.bTalking == false)
            {
                gameObject.GetComponent<UnitStatus>().m_unitData.fCurChat = 0.0f;
                ResourceMgr.GetInstance().CreateChatBubble(gameObject, CHATBUBBLE_STATE.NORMAL);
                gameObject.GetComponent<UnitStatus>().m_unitData.bTalking = true;
            }

        }
        else if (state == CHATBUBBLE_STATE.EVENT)
        {
            ResourceMgr.GetInstance().CreateChatBubble(gameObject, CHATBUBBLE_STATE.EVENT, SceneID, Log_Num);
            gameObject.GetComponent<UnitStatus>().m_unitData.bTalking = true;
        }

        else
        {
            if (Random.Range(0, 5) == 0 && gameObject.GetComponent<UnitStatus>().m_unitData.bTalking == false)
            {
                gameObject.GetComponent<UnitStatus>().m_unitData.bTalking = true;

                switch (state)
                {
                    case CHATBUBBLE_STATE.ATTACK:
                        ResourceMgr.GetInstance().CreateChatBubble(gameObject, CHATBUBBLE_STATE.ATTACK);
                        break;

                    case CHATBUBBLE_STATE.HURT:
                        ResourceMgr.GetInstance().CreateChatBubble(gameObject, CHATBUBBLE_STATE.HURT);
                        break;
                }
            }
        }



    }
}
